;
(function() {
	var crypto = require('crypto');
	var Buffer = require('buffer').Buffer

	var core = {
		toACIStr: function(str) {
			var buf = new Buffer(1024);
			var len = buf.write(str, 0);
			return buf.toString('binary', 0, len);
		},
		sortStr: function(obj, is_encode) {
			var keys = Object.keys(obj);
			keys.sort();
			var key_arr = [];
			keys.forEach(function(key) {
				var value = obj[key];
				if (value) {
					key_arr.push(key + "=" + (is_encode ? encodeURIComponent(value) : value));
				}
			});
			var sign_str = key_arr.join("&");
			return sign_str;
		},
		sha1: function(obj) {
			obj = core.toACIStr(typeof obj === "string" ? obj : core.sortStr(obj));
			return crypto.createHash('sha1').update(obj).digest("hex");
		},
		sign: function(obj, key) {
			var sign_str = core.sortStr(obj, true);
			sign_str += "&key=" + key;
			sign_str = core.toACIStr(sign_str);
			console.log(sign_str);
			// console.log();
			// sign_str = core.toACIStr(sign_str);
			return crypto.createHash('md5').update(sign_str).digest('hex').toUpperCase();
		}
	};
	module.exports = core;

	// var sign = core.sign({
	// 	"appid": "wxcf74f930098faee1",
	// 	"mch_id": "1233472902",
	// 	"nonce_str": "sq8x3mfyderyhkt9",
	// 	"body": "来自“dotnar_d1”的订单",
	// 	"detail": "支付测试",
	// 	"out_trade_no": "PA_A_61v52bg2",
	// 	"spbill_create_ip": "113.89.185.15",
	// 	"notify_url": "http://api.dotnar.com/wc/order_notify",
	// 	"total_fee": 10,
	// 	"trade_type": "JSAPI",
	// 	"openid": "o_QrEjiA5Yvgp3N4HnKhy9O5J1mU",
	// }, "77ff4d4b3f861ebacfe1de20c497c411");
	// console.log(sign);
	// // var sign = core.sign({
	// // 	"appid": "123",
	// // }, "77ff4d4b3f861ebacfe1de20c497c411");
	// // console.log(sign);
	// var sign_str = "appid=wxcf74f930098faee1&body=%E6%9D%A5%E8%87%AA%E2%80%9Cdotnar_d1%E2%80%9D%E7%9A%84%E8%AE%A2%E5%8D%95&detail=%E6%94%AF%E4%BB%98%E6%B5%8B%E8%AF%95&mch_id=1233472902&nonce_str=adpqhv3znis5rk9&notify_url=http%3A%2F%2Fapi.dotnar.com%2Fwc%2Forder_notify&openid=o_QrEjiA5Yvgp3N4HnKhy9O5J1mU&out_trade_no=PA_A_61v52bg2&spbill_create_ip=113.89.185.15&total_fee=10&trade_type=JSAPI&key=77ff4d4b3f861ebacfe1de20c497c411";
	// console.log(crypto.createHash('md5').update(sign_str).digest('hex').toUpperCase());
	// var sign_str = "appid=wxd930ea5d5a258f4f&auth_code=123456&body=test&device_info=123&mch_id=1900000109&nonce_str=960f228109051b9969f76c82bde183ac&out_trade_no=1400755861 &spbill_create_ip=127.0.0.1&total_fee=1&key=8934e7d15453e97507ef794cf7b0519d";
	// console.log(crypto.createHash('md5').update(sign_str).digest('hex').toUpperCase());
}());